/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.dao.impl;

import vip.dexian.admin.dao.RoleDao;
import vip.dexian.admin.dao.RoleDepartmentDao;
import vip.dexian.admin.dto.AdminRoleDTO;
import vip.dexian.admin.entity.Role;
import vip.dexian.common.utils.NumberUtils;
import vip.dexian.core.base.dao.BaseDaoImpl;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;

/**
 * 角色DaoImpl
 *
 * @author 挺好的 2023年06月02日 08:45:40
 */
@Repository ("roleDaoImpl")
public class RoleDaoImpl extends BaseDaoImpl <Role, Long> implements RoleDao {

    /**
     * 角色关联的部门
     */
    @Resource (name = "roleDepartmentDaoImpl")
    private RoleDepartmentDao roleDepartmentDao;

    /**
     * 根据admin id 查找角色
     *
     * @param adminId
     *         管理员id
     *
     * @return {@link vip.dexian.admin.dto.AdminRoleDTO }
     */
    @Override
    public List <AdminRoleDTO> findByAdmin (Long adminId) {

        if (!NumberUtils.isPositive(adminId)) {
            return Collections.emptyList();
        }

        String jpql = """
                SELECT new vip.dexian.admin.dto.AdminRoleDTO(a.id,r.id, r.name, r.identity, r.dataScope, r.authorities) FROM Role r LEFT JOIN r.admins AS a WHERE a.id=:adminId
                """;

        return this.entityManager.createQuery(jpql).setParameter("adminId", adminId).getResultList();
    }

    /**
     * 根据adminId查找角色id
     *
     * @param adminId
     *         管理员id
     *
     * @return 角色id列表
     */
    @Override
    public List <Long> findIdByAdmin (Long adminId) {
        List <AdminRoleDTO> roles = this.findByAdmin(adminId);

        if (CollectionUtils.isEmpty(roles)) {
            return Collections.emptyList();
        }

        return roles.stream().map(AdminRoleDTO::getRoleId).toList();
    }
}

